<template>
  <div class="page">
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <div style="display: flex; align-items: center">
          <span>商户添加：</span>
          <select-page
            ref="modelRpiSelect"
            label="rpiName"
            value="rpiNo"
            :select.sync="modelForm.rpiNo"
            :url="website.searchLink.merchantUrl"
            placeholder-text="商户"
            filter-key="searchParam"
          ></select-page>
          <div style="margin-left: 10px">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="handleAdd"
              >添 加
            </el-button>
          </div>
        </div>
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          icon="el-icon-folder-add"
          plain
          @click="excelBox = true"
          >批量添加
        </el-button>
      </template>
      <template slot-scope="{}" slot="serviceNoForm">
        <!-- <select-page
            ref="searchSerSelect"
            label="serviceName"
            value="serviceNo"
            :select.sync="form.serviceNo"
            :url="website.searchLink.serviceUrl"
            placeholder-text="服务商"
            filter-key="searchParam"
          ></select-page> -->
      </template>
      <!-- <template slot-scope="{}" slot="serviceNoSearch">
          <select-page
            ref="searchSerSelect"
            label="serviceName"
            value="serviceNo"
            :select.sync="search.serviceNo"
            :url="website.searchLink.serviceUrl"
            placeholder-text="服务商"
            filter-key="searchParam"
          ></select-page>
      </template> -->
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>
    </avue-crud>
    <!-- 导入 -->
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      v-if="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :before-close="handleCloseExcel"
        ref="excelForm"
      >
        <template slot="excelFile">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :limit="1"
            :http-request="httpRequest"
            :on-success="onSuccess"
            :on-change="handleChange"
            :on-remove="handleRemove"
            multiple
            :file-list="fileList"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              请上传 .xls,.xlsx 标准格式文件
            </div>
          </el-upload>
          <div style="display: flex; justify-content: flex-end">
            <el-button
              type="primary"
              @click="uploadSubmit"
              :disabled="uploadDisabled"
              v-show="fileList.length"
            >
              确定上传<i class="el-icon-upload2 el-icon--right"></i>
            </el-button>
          </div>
        </template>
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  merchantList,
  addMerchant,
  delMerchant,
  getExportTemplate,
  uploadFile,
} from "@/api/rb-oem/ticket/ticket";
import { downloadFileExcel } from "@/util/util";
export default {
  props: {
    serviceArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
    id: {
      type: [Number, String],
      default: "",
    },
    rpiNo: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      screenWidth: document.documentElement.clientWidth,
      data: [],
      search: {},
      form: {},
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        allPrice: 0,
      },
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      option: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: false,
        editBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "商户编号",
            searchLabel: "商户查询",
            prop: "rpiNo",
            slot: true,
            overHidden: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户",
                trigger: "blur",
              },
            ],
          },
          // {
          //   label: "服务商编号",
          //   prop: "serviceNo",
          //   slot: true,
          //   overHidden: true,
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入服务商编号",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          // {
          //   label: "",
          //   prop: "hasChild",
          //   type: "checkbox",
          //   multiple: false,
          //   dataType: "string",
          //   showColumn: false,
          //   hide: true,
          //   dicData: [
          //     {
          //       label: "包含下级",
          //       value: 1
          //     }
          //   ]
          // },
          {
            label: "商户名称",
            prop: "rpiName",
            overHidden: true,
            display: false,
          },
          {
            label: "创建时间",
            prop: "createTime",
            overHidden: true,
            display: false,
          },
        ],
      },
      dialogModel: {
        type: "",
        text: "",
        visible: false,
        subText: "",
        url: "/comppage/getlist/pageServiceName",
        oLabel: "names",
        oValue: "codes",
      },
      modelForm: {
        rpiNo: "",
        ticketCode: "",
      },
      rowType: "add",
      uploadDisabled: false,
      fileList: [],
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              url: "link",
              // name: "originalName",
              res: "data",
            },
            headers: {
              "Content-Type": "multipart/form-data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/ticket/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  watch: {
    serviceArr: {
      handler(arr) {
        this.tableData = arr;
        if (arr.length > 0) {
          this.dataList = arr;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  //   activated () {
  //     this.refreshList()
  //   },
  methods: {
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    beforeOpen(done, type) {
      if (["add"].includes(type)) {
      }
      done();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      if (this.rowType === "add") {
        addMerchant({ ...row, mealCode: this.mealCode }).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            loading();
          }
        );
      } else if (this.rowType === "del") {
        delMerchant({ ...row, mealCode: this.mealCode }).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            loading();
          }
        );
      }
    },
    handleAdd() {
      // this.rowType = 'add'
      // this.$refs.crud.rowAdd();
      addMerchant({ id: this.id, rpiNo: this.modelForm.rpiNo, addType: '1' }).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    handleDelete() {
      this.rowType = "del";
      this.$refs.crud.rowAdd();
    },
    rowUpdate(row, index, done, loading) {
      this.$nextTick(() => {
        this.inputForm.productList[index] = Object.assign(
          this.inputForm.productList[index],
          {
            ...row,
          }
        );
      });
      setTimeout(() => {
        done();
      }, 300);
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delMerchant({
            id: row.id,
          });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    uploadSubmit() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    /* 关闭弹框 */
    handleCloseExcel(done) {
      this.excelForm = {};
      this.fileList = [];
      done();
    },
    /* 批量文件上传 */
    httpRequest(option) {
      this.$refs.excelForm.validate((valid, done, msg) => {
        if (valid) {
          this.uploadDisabled = true;
          let params = {
            id: this.id,
          };
          uploadFile(option.file, option.file.name, params).then(
            (res) => {
              this.uploadDisabled = false;
              this.excelBox = false;
              this.$message({ type: "success", message: res.data.msg });
              this.page.currentPage = 1;
              this.onLoad(this.page);
              done();
            },
            () => {
              this.uploadDisabled = false;
            }
          );
        } else {
          return false;
        }
      });
    },
    handleTemplate() {
      getExportTemplate().then((res) => {
        downloadFileExcel(res);
      });
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
    onLoad(page, params = {}) {
      this.loading = true;
      console.log(this.id);
      console.log(this.rpiNo);
      merchantList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, { id: this.id })
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style scoped>
.z_flex {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>